package com.meelive.ingkee.push.platform.hms

import android.content.Context
import android.os.Handler
import android.os.Looper
import android.util.Log
import com.meelive.ingkee.push.platform.IPush
import com.meelive.ingkee.push.model.InkePushType
import com.meelive.ingkee.push.InkePushConfig
import com.meelive.ingkee.push.common.PushUtils
import com.meelive.ingkee.push.model.Constance
import com.meelive.ingkee.push.InkePushHelper
import com.huawei.hms.aaid.HmsInstanceId
import com.huawei.hms.common.ApiException
import java.util.concurrent.Executor
import java.util.concurrent.Executors

/**
 * Create by: fanfeiyue
 * on: 2019-08-22
 * desc:
 */
class InkeHMSPush : IPush() {

    private val mExecutor: Executor by lazy { Executors.newSingleThreadExecutor() }
    private val mHandler: Handler by lazy { Handler(Looper.getMainLooper()) }

    override fun getPushType(): InkePushType {
        return InkePushType.HMSPUSH
    }

    //    调用getToken接口后，Token不是在本接口中直接返回的，而是通过广播的形式通知APP因此需要开发者实现自定义广播的onToken方法来接收Token。
    override fun onRegister(context: Context, config: InkePushConfig) {

        if (PushUtils.DEBUG) {
            Log.d(Constance.TAG, "InkeHMSPush onRegister")
        }
        if (!PushUtils.emuiLevelAboveFive() || !PushUtils.isInStallHMS(context)) {
            InkePushHelper.getInstance().onErrorResponse(InkePushType.HMSPUSH, Constance.PUSH_NOT_SUPPORT, Constance.PUSH_NOT_SUPPORT_MSG)
            return
        }
        mExecutor.execute {
            try {
                val token = HmsInstanceId.getInstance(context).getToken(config.hwAppId, "HCM")
                mHandler.post {
                    InkePushHelper.getInstance().onReceiveToken(InkePushType.HMSPUSH, token)
                }
            } catch (e: ApiException) {
                InkePushHelper.getInstance().onErrorResponse(InkePushType.HMSPUSH, e.statusCode.toLong(), e.message)
            }
        }
    }

    override fun onUnregister(context: Context, config: InkePushConfig) {
        mExecutor.execute {
            try {
                HmsInstanceId.getInstance(context).deleteToken(config.hwAppId, "HCM")
            } catch (e: ApiException) {
                e.printStackTrace()
            }
        }
    }
}